<?php
/**
 * 第三方相关特定函数
 */
namespace Admin\Model;

use Common\Model\UtilsModel;
use Think\Exception;
use Think\Model;
class ThirdModel extends Model{
	const SUCCESS   =0;//成功
	const FAILURE   =1;//失败

	const POWER_MODULE=1;//星悦

	//权限项type字段
	const POWER_TYPE_MAIN_TOP		= 1;//表示显示主菜单和顶部菜单
	const POWER_TYPE_NO_MAIN_NO_TOP= 2;//表示不显示主菜单及顶部菜单
	const POWER_TYPE_NO_PAGE		= 3;//表示权限配置项
	const POWER_TYPE_NO_MAIN_TOP	= 4;//表示不显示主菜单但显示顶部菜单



	public static function set_session($key,$value){
		if($key){
			if($key=="uid"){
				$key="admin_uid";
			}
			$_SESSION[$key]=$value;
		}
	}

 	public static function  get_session($key){
		if($key=="uid"){
			$key="admin_uid";
		}
		if(isset($_SESSION[$key])){
			if($key=="permit_id"){


				$roleId=ThirdModel::get_session("role_id");
				return self::get_permit_by_role_id($roleId);
			}
			return $_SESSION[$key];
		}
		return null;
	}

	static $_role_quicklink_mappingM=null;
	/**
	 * 获取quicklinkMapping
	 * Author: shijy
	 * @return \Model|null|Model
	 */
	private function getQuicklinkMappingM(){
		if(!self::$_role_quicklink_mappingM){
			self::$_role_quicklink_mappingM=M('role_quicklink_mapping',null,'DB_OTHER_CFG');
		}
		return self::$_role_quicklink_mappingM;
	}

	static $_role_permit_mappingM=null;
	/**
	 * 获取quicklinkMapping
	 * Author: shijy
	 * @return \Model|null|Model
	 */
	private function getRolePermitMappingM(){
		if(!self::$_role_permit_mappingM){
			self::$_role_permit_mappingM = M('role_permit_mapping',null,'DB_OTHER_CFG');
		}
		return self::$_role_permit_mappingM;
	}



	static $_wap_admin_menuM=null;
	/**
	 * 获取quicklinkMapping
	 * Author: shijy
	 * @return \Model|null|Model
	 */
	private function getWapAdminMenuM(){
		if(!self::$_wap_admin_menuM){
			self::$_wap_admin_menuM = M('wap_admin_menu',null,'DB_OTHER_CFG');
		}
		return self::$_wap_admin_menuM;
	}



	public static function get_quicklink_by_role_id($id){
		return self::getQuicklinkMappingM()->where("role_id={$id}")->getField('page_id',true);
		//return $this->db->get_array("select page_id from role_quicklink_mapping where role_id=$id",1,"page_id",0);
	}

	public static function get_quicklinkinfo_by_role_id($id){
		return self::getQuicklinkMappingM()->join("left join wap_admin_menu on role_quicklink_mapping.page_id=wap_admin_menu.nid")
			->where("role_id={$id}")->getField('page_id,title,class',true);
		//return $this->db->get_array("select page_id,title,class from role_quicklink_mapping as RQM left join wap_admin_menu as WAM on RQM.page_id=WAM.nid where role_id=$id");
	}

	/**
	 * 获取角色的权限
	 * Author: shijy
	 * @param $id
	 * @return mixed
	 */
	public static function get_permit_by_role_id($id){
		return self::getRolePermitMappingM()->where("role_id={$id}")->getField("permit_id",true);
		/*
		$ar=$this->db->get_array("select permit_id from role_permit_mapping where role_id=$id");
		$r=array();
		if(is_array($ar)){
			foreach($ar as $value){
				$r[]=$value['permit_id'];
			}
		}
		return $r;
		*/
	}


	/**
	 * 获取管理后台菜单
	 * Author: shijy
	 * @return mixed
	 * @throws Exception
	 */
	public static function get_menu(){
		$permit_id=self::get_session("permit_id");
		if(self::get_session("SUPERID")){
			return  self::getWapAdminMenuM()->where('module='.self::POWER_MODULE.' and type=1 and status=1')->order('sort asc')->select();


			//return $this->db->get_array("select * from `wap_admin_menu` where type=1 and status=1 order by sort asc");
		}
		elseif(is_array($permit_id) && !empty($permit_id)){
			$permit_id=implode(",", $permit_id);
			return self::getWapAdminMenuM()->where('module='.self::POWER_MODULE." and nid in ($permit_id) and type=1 and status=1")->order('sort asc')->select();
		}
		else{
			return null;
		}
	}


	public static function get_admin_menu(){
		$menu=self::get_menu();
		$row=array();
		foreach($menu as $key=>$value){
			if($value['base_id']==0){
				$row[]=$value;
				unset($menu[$key]);
				$row[(count($row)-1)]['child_menu']=self::parse_menu($menu,$value['nid']);
			}
		}
		return $row;
	}


	public static function set_admin_menu($menu){
		$menu_out='';
		foreach($menu as $key=>$value){

			if($value['type']!=3 && $value['child_menu']){
				$menu_out.="<li><dl><dt class='".$value['class']."'>".$value['title']."</dt>";
				if($value['child_menu']){
					foreach($value['child_menu'] as $key=>$value){
						$menu_out.="<dd id='link_".$value['nid']."'><a  href='".U($value['manage_content_page'])."' target='subContent' onclick='openLoading()' >".$value['title']."</a></dd>";
					}
				}
				$menu_out.="</dl></li>";
			}
		}
		return $menu_out;
	}

	/**
	 * 组合子菜单项
	 * Author: shijy
	 * @param $result
	 * @param $father_id
	 * @return array
	 */
	public static function 	parse_menu(&$result,$father_id){
		foreach($result as $key=>$value){
			if($value['base_id']==$father_id){
				$row[]=$value;
				unset($result[$key]);
			}
		}
		if(isset($row)){
			return $row;
		}
	}


	/**
	 * 获取同类下最大菜单编号
	 * Author: shijy
	 * @param $menus
	 * @param $base_id
	 * @return int|mixed
	 */
	private static function getMaxNid(&$menus,$base_id){
		$max=0;
		foreach($menus as $one){
			if($one['base_id']==$base_id){
				$max=max($max,$one['nid']);
			}
		}
		if($max==0){
			$max=$base_id*1000;
		}
		return $max;
	}

	/**
	 * 复制权限荐到聚星
	 * Author: shijy
	 */
	public static function copyMenuToOther(){
		$oldMenu=M('gm_sys_node',null,DB_GM_CFG)->where("path like '216/%'")->order('level asc')->select();
		$second =array();
		$third  =array();
		foreach($oldMenu as $one){
			switch($one['level']+0){
				case 2://二级
					if($one['is_menu']==1){
						$second[$one['id']]   = $one;
					}
					break;
				case 3://三级
					$third[]    = $one;
					break;
			}
		}



		$adminMenuM=M('wap_admin_menu',null,DB_OTHER_CFG);
		$existMenu=$adminMenuM->where('module='.ThirdModel::POWER_MODULE)->select();
		$existMenuMap = array();
		//允许本系统添加权限菜单的起始编号，50-69星悦，70-89其它
		$secondBegin=50;
		foreach($existMenu as $one){
			$existMenuMap[$one['outId']]=$one;
			$secondBegin=max($one['nid'],$secondBegin);
		}
		unset($existMenu);




		//////二级菜单
		foreach($second as $one){
			if(!array_key_exists($one['id'],$existMenuMap)) {//如果不存在
				$secondBegin++;
				$new = array(
					'nid'=>$secondBegin,
					'base_id' => 0,
					'status' => 1,
					'title' => $one['title'],
					'manage_content_page' => '',
					'desc' => '',
					'class' => $one['classname'].'',
					'sort' => $secondBegin,
					'module' => ThirdModel::POWER_MODULE,
					'outId' => $one['id']
				);
				if($one['is_menu']){
					$new['type']=ThirdModel::POWER_TYPE_MAIN_TOP;
				}else{
					$new['type']=ThirdModel::POWER_TYPE_NO_PAGE;
				}
				$new['manage_content_page']=getAllPathMenu($one['path']);
				$nid=$adminMenuM->add($new);
				$second[$one['id']]['newId']=$secondBegin;
			}else{
				$second[$one['id']]['newId']=$existMenuMap[$one['id']]['nid'];
			}
		}

		$maxMap=array();

		//////三级菜单
		$addData=array();
		foreach($third as $one){
			if(!array_key_exists($one['id'],$existMenuMap)) {//如果不存在
				$baseId=$second[$one['pid']]['newId'];
				if(!$baseId){//如果没有上级菜单，取跳过
					continue;
				}
				if(array_key_exists($baseId,$maxMap)){
					$maxMap[$baseId]++;
					$nid=$maxMap[$baseId];
				}else{
					$maxMap[$baseId]=self::getMaxNid($existMenuMap,$baseId)+1;
					$nid=$maxMap[$baseId];
				}


				$new = array(
					'nid'=> $nid,
					'base_id' => $baseId,
					'status' => 1,
					'title' => $one['title'],
					'manage_content_page' => '',
					'desc' => '',
					'class' => $one['classname'].'',
					'sort' => $one['sort'],
					'module' => ThirdModel::POWER_MODULE,
					'outId' => $one['id']
				);

				if($one['is_menu']){
					$new['type']=ThirdModel::POWER_TYPE_MAIN_TOP;
				}else{
					$new['type']=ThirdModel::POWER_TYPE_NO_PAGE;
				}
				$new['manage_content_page']=getAllPathMenu($one['path']);
				$addData[]=$new;
			}
		}



		if(count($addData)>0){
			$adminMenuM->addAll($addData);
		}
	}


	/**
	 * 推送权限项到第三方
	 * Author: shijy
	 */
	public static function pushPowerToOther()
	{
		//  1.社区运营 511
		//  2.统计分析 530
		//  3.系统配置  512
		$group=array(
			1=>511,
			2=>530,
			3=>512
		);
		$oldMenu = M('gm_sys_node', null, DB_GM_CFG)->where("path like '216/%' and pid not in(385,272) and id not in (385,272)")->order('level asc,id asc')->select();
		$second = array();
		$third  = array();
		$addData = array();

		$addData[]=array(
			'nid' => 511,
			'parentId' => 0,
			'title' => '社区运营',
			'value' => '',
			'module' => ThirdModel::POWER_MODULE,
			'is_menu' => 1
		);
		$addData[]=array(
			'nid' => 530,
			'parentId' => 0,
			'title' => '统计分析',
			'value' => '',
			'module' => ThirdModel::POWER_MODULE,
			'is_menu' => 1
		);
		$addData[]=array(
			'nid' => 512,
			'parentId' => 0,
			'title' => '系统配置',
			'value' => '',
			'module' => ThirdModel::POWER_MODULE,
			'is_menu' => 1
		);

		foreach ($oldMenu as $k=>$one) {

			if(in_array($one['id']+0,$group)){

				unset($oldMenu[$k]);
				continue;
			}
			switch ($one['level'] + 0) {
				case 2://二级
					//if($one['is_menu'] == 1){
						$second[$one['id']] = $one;
					//}
					break;
				case 3://三级
					$third[] = $one;
					break;
			}
		}

		foreach ($third as $one) {
			if($one['is_menu']){
				if(array_key_exists($one['pid'],$second)) {
					$second[$one['pid']]['path'] = $one['path'];
				}
			}
		}


		//////二级菜单
		foreach ($second as $one) {
			$new = array(
				'nid' => $one['id'],
				'parentId' =>$group[$one['group']],
				'title' => $one['title'],
				'value' => '',
				'module' => ThirdModel::POWER_MODULE,
				'is_menu' => 1
			);
			$new['value']=getAllPathMenu($one['path']);
			$addData[] = $new;
		}

		//////三级菜单

		foreach ($third as $one) {
			$new = array(
				'nid' => $one['id'],
				'parentId' => $one['pid'],
				'title' => $one['title'],
				'value' => '',
				'module' => ThirdModel::POWER_MODULE,
				'is_menu' =>$one['is_menu']
			);
			$new['value'] = getAllPathMenu($one['path']);
			$addData[] = $new;
		}
		
		$uReturn=UtilsModel::broadcast('push_power',$addData,'czk');
		return $uReturn;
	}


	public function checkPower($action){
		if(ThirdModel::get_session("SUPERID")){
			return true;
		}

		$nid=self::getNidByAction($action);
		return self::check_permit($nid);
	}

	/**
	 * 权限控制
	 * Author: shijy
	 * @param $permit_id
	 * @param int $type
	 * @return bool
	 * @throws Exception
	 */
	public static function check_permit($permit_id,$type=0){//$type=0表示表单提交，=1表示打开表单
		if(ThirdModel::get_session("SUPERID")){
			return true;
		}
		elseif(!is_array(ThirdModel::get_session("permit_id"))){
			return false;
		}
		elseif(is_array($permit_id)){
			if(!array_intersect($permit_id, ThirdModel::get_session("permit_id"))){
				return false;
			}
		}
		elseif(!in_array($permit_id,ThirdModel::get_session("permit_id"))){
			return false;
		}
		return true;
	}

	/**
	 * 根据当前controller,action获取对应的nid
	 * Author: shijy
	 * @param $action
	 * @return mixed
	 */
	public static function getNidByAction($action){
		return self::getWapAdminMenuM()->where('module='.self::POWER_MODULE." and manage_content_page like '%{$action}'")->getField('nid');
	}
}